package com.lanyou.esb.cook.proxy.redis.proxy.impl;

import java.io.IOException;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.lanyou.esb.cook.proxy.common.Constants4Redis;
import com.lanyou.esb.cook.proxy.redis.JedisPoolUtils;
import com.lanyou.esb.cook.proxy.redis.proxy.base.BaseStrJedisProxy;

/**
 * 接口告警工单号REDIS处理器
 * 
 * @author Davey.wu
 */
public class WorkOrderNoJedisProxy extends BaseStrJedisProxy<Long> {
	/** 接口告警工单流水号前缀 **/
	public static final String KEYS_SUFFIX = Constants4Redis.PREFIX_WONO;

	public WorkOrderNoJedisProxy() {
		this.setTimeOut(Constants4Redis.REDIS_TIMEOUT_WONO);
	}

	@Override
	public String getKey(String field) {
		return KEYS_SUFFIX + KEY_SEPARATOR + field;
	}

	@Override
	public String getKeyFromObject(Long target) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Long get(String key) throws JedisException, JsonParseException,
			JsonMappingException, IOException {
		long result = 0;
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return 0l;
		}
		boolean broken = false;
		try {
			Long value = jedis.incr(key);
			if (value != null && value.longValue() == 1) {
				jedis.expire(key, this.getTimeOut());
			}
			if (value != null) {
				result = value;
			}
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		return result;
	}

	@Override
	public long setex(String key, Long target) throws JedisException,
			JsonProcessingException {
		long value = 0;
		if (target != null) {
			value = target.longValue();
		}
		long result = 0;
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return 0l;
		}
		boolean broken = false;
		try {
			jedis.expire(key, this.getTimeOut());
			result = jedis.incrBy(key, value);
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}

		return result;
	}

}
